package com.jianguozh.difs.support.service.utils;

import cn.hutool.core.util.ClassUtil;
import com.jianguozh.difs.framework.annotation.EnumDesc;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 枚举工具类
 *
 * @author hanrs
 * @email 4076130@qq.com
 * @since 2022/4/8 16:15
 */
@Slf4j
public class EnumUtils {

    public static Map<String, Map> getEnums(String packageName) {
        Set<Class<?>> classes = ScanUtils.scanClass(packageName, true);
        HashMap<String, Map> enums = new HashMap<>();

        for (Class<?> aClass : classes) {
            if (ClassUtil.isEnum(aClass)) {
                Class<Enum> em = (Class<Enum>) aClass;
                // 枚举类里面必须是 value 和displayName
                Method valueMethod = ClassUtil.getDeclaredMethod(aClass, "getValue");
                Method displayNameMethod = ClassUtil.getDeclaredMethod(aClass, "getDisplayName");
                EnumDesc enumDesc = em.getDeclaredAnnotation(EnumDesc.class);
                if (valueMethod == null || displayNameMethod == null) {
                    continue;
                }
                //得到enum的所有实例
                Object[] objs = em.getEnumConstants();
                Map<String, Object> item = new HashMap<>();
                item.put("title", enumDesc != null ? enumDesc.title() : "未定义");
                Map map = new HashMap();
                for (Object obj : objs) {
                    try {
                        map.put(valueMethod.invoke(obj), displayNameMethod.invoke(obj));
                    } catch (IllegalAccessException e) {
                        log.error("Invoke enum method occurs exception", e.getMessage());
                    } catch (InvocationTargetException e) {
                        log.error("Invoke enum method occurs exception", e.getMessage());
                    }
                }
                item.put("list", map);
                enums.put(em.getSimpleName(), item);
            }
        }
        return enums;
    }

    public static void main(String[] args) {
        Map map = getEnums("com.jianguozh.difs.**.enums");
        System.out.println(map);
    }

}
